package com.ruoyi.project.setsystem.companydept.service;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.web.domain.Ztree;
import com.ruoyi.project.setsystem.companydept.domain.CompanyDept;
import com.ruoyi.project.setsystem.companydept.mapper.CompanyDeptMapper;
import com.ruoyi.project.setsystem.rolepower.domain.RolePower;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.role.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 大帅比
 * @date 2020-09-19 14:08
 * @desc 百战程序员 http://www.itbaizhan.com
 */
@Service
public class CompanyDeptServiceImpl implements ICompanyDeptService {
    @Autowired
    private CompanyDeptMapper companyDeptMapper;
    @Override
    public List<CompanyDept> All(CompanyDept companyDept) {
        return companyDeptMapper.All(companyDept);
    }


    @Override
    public List<Ztree> selectDeptTree(CompanyDept companyDept)
    {
        List<CompanyDept> deptList = companyDeptMapper.All(companyDept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *

     */
    @Override
    public List<Ztree> roleDeptTreeData(RolePower rolePower)
    {
        Long roleId = rolePower.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<CompanyDept> deptList = All(new CompanyDept());
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleDeptList = companyDeptMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        }
        else
        {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<CompanyDept> deptList)
    {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<CompanyDept> deptList, List<String> roleDeptList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (CompanyDept companyDept : deptList)
        {
            if (UserConstants.DEPT_NORMAL.equals(companyDept.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(companyDept.getDeptId());
                ztree.setpId(companyDept.getParentId());
                ztree.setName(companyDept.getDeptName());
                ztree.setTitle(companyDept.getDeptName());
                if (isCheck)
                {
                    ztree.setChecked(roleDeptList.contains(companyDept.getDeptId() + companyDept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId)
    {
        CompanyDept companyDept = new CompanyDept();
        companyDept.setParentId(parentId);
        return companyDeptMapper.selectDeptCount(companyDept);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = companyDeptMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        return companyDeptMapper.deleteDeptById(deptId);
    }

    /**
     * 新增保存部门信息

     */
    @Override
    public int insertDept(CompanyDept companyDept)
    {
        CompanyDept info = companyDeptMapper.selectDeptById(companyDept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new BusinessException("部门停用，不允许新增");
        }
        companyDept.setCreateBy(ShiroUtils.getLoginName());
        companyDept.setAncestors(info.getAncestors() + "," + companyDept.getParentId());
        return companyDeptMapper.insertDept(companyDept);
    }

    /**
     * 修改保存部门信息

     */
    @Override
    @Transactional
    public int updateDept(CompanyDept companyDept)
    {
        CompanyDept newParentDept = companyDeptMapper.selectDeptById(companyDept.getParentId());
        CompanyDept oldDept = selectDeptById(companyDept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            companyDept.setAncestors(newAncestors);
            updateDeptChildren(companyDept.getDeptId(), newAncestors, oldAncestors);
        }
        companyDept.setUpdateBy(ShiroUtils.getLoginName());
        int result = companyDeptMapper.updateDept(companyDept);
        if (UserConstants.DEPT_NORMAL.equals(companyDept.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(companyDept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态

     */
    private void updateParentDeptStatus(CompanyDept companyDept)
    {
        String updateBy = companyDept.getUpdateBy();
        companyDept = companyDeptMapper.selectDeptById(companyDept.getDeptId());
        companyDept.setUpdateBy(updateBy);
        companyDeptMapper.updateDeptStatus(companyDept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<CompanyDept> children = companyDeptMapper.selectChildrenDeptById(deptId);
        for (CompanyDept child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            companyDeptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 部门ID
     * @param ancestors 元素列表
     */
    public void updateDeptChildren(Long deptId, String ancestors)
    {
        CompanyDept companyDept = new CompanyDept();
        companyDept.setParentId(deptId);
        List<CompanyDept> childrens = companyDeptMapper.All(companyDept);
        for (CompanyDept children : childrens)
        {
            children.setAncestors(ancestors + "," + companyDept.getParentId());
        }
        if (childrens.size() > 0)
        {
            companyDeptMapper.updateDeptChildren(childrens);
        }
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public CompanyDept selectDeptById(Long deptId)
    {
        return companyDeptMapper.selectDeptById(deptId);
    }

    /**
     * 校验部门名称是否唯一
     *

     */
    @Override
    public String checkDeptNameUnique(CompanyDept companyDept)
    {
        Long deptId = StringUtils.isNull(companyDept.getDeptId()) ? -1L : companyDept.getDeptId();
        CompanyDept info = companyDeptMapper.checkDeptNameUnique(companyDept.getDeptName(), companyDept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

}
